package com.jdk.demo.fileChannel.batchRead;

import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

// read(ByteBuffer[])作用是将字节序列从此通道读入给定的缓冲区数组中的第0个缓冲区的当前位置
// read(ByteBuffer[])方法实现的是ScatteringByteChannel接口中的同名方法，而接口ScatteringByteChannel的父接口是ReadableByteChannel，说明接口ScatteringByteChannel具有ReadableByteChannel接口的以下两个特性
// 1、将通道当前位置中的字节序列读入1个ByteBuffer缓冲区的remaining空间中
// 2、read方法是同步的
// 3、还有第三个特性：将通道当前位置的字节序列读入多个ByteBuffer缓冲区的remaining剩余空间中
public class Test4_1 {

	private static FileInputStream fisRef;
	private static FileChannel fileChannel;
	
	// 验证read方法返回值的意义
	public static void main(String[] args) throws Exception {
		fisRef = new FileInputStream(new File("d.txt"));
		fileChannel = fisRef.getChannel();
		
		ByteBuffer buffer1 = ByteBuffer.allocate(2);
		ByteBuffer buffer2 = ByteBuffer.allocate(2);
		ByteBuffer[] bufferArray = new ByteBuffer[]{buffer1, buffer2};
		
		long readLength = fileChannel.read(bufferArray);
		System.out.println(readLength); // 取得4个字节
		buffer1.clear();
		buffer2.clear();
		
		readLength = fileChannel.read(bufferArray);
		System.out.println(readLength); // 取得1个字节
		buffer1.clear();
		buffer2.clear();
		
		readLength = fileChannel.read(bufferArray);
		System.out.println(readLength); // -1，因为到达文件流末尾
		buffer1.clear();
		buffer2.clear();
		
		fileChannel.close();
		fisRef.close();
	}
	
}
